package cn.epsilon3.configuration;

import cn.epsilon3.common.E3BaseService;
import cn.epsilon3.constant.Base;
import cn.epsilon3.constant.E3CacheKeyEnum;
import cn.epsilon3.domain.e3.po.E3RolePo;
import cn.epsilon3.domain.e3.vo.E3ResourceVO;
import cn.epsilon3.mybatis.mapper.E3ResourceMapper;
import cn.epsilon3.mybatis.service.E3RoleMapperService;
import cn.epsilon3.utils.CollectionsUtils;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @description 系统组件自动配置
 *
 * @author: epsilon3
 * @date: 2023/12/6 9:46
 */
@Configuration
public class E3SystemConfiguration extends E3BaseService {

    private static final Log log = LogFactory.get();

    @Resource
    private E3ResourceMapper resourceMapper;

    @Resource
    private E3RoleMapperService roleMapperService;

    /**
     * 初始化各个角色对应菜单树
     *
     * @return map key为角色id，value为对应菜单树
     */
    private ConcurrentHashMap<String, List<E3ResourceVO>> loadMenuTree() {
        log.info("---------------------开始初始化资源树---------------------");
        ConcurrentHashMap<String, List<E3ResourceVO>> menuTreeMap = initConcurrentHashMapForValueList(String.class, E3ResourceVO.class);
        List<E3RolePo> e3RolePoList = roleMapperService.selectAll();
        if (CollectionUtil.isNotEmpty(e3RolePoList)) {
            e3RolePoList.forEach(e3RolePo -> {
                log.info("---------------------加载{}角色资源树---------------------", e3RolePo.getRoleName());
                String roleId = e3RolePo.getId();
                List<E3ResourceVO> resourceVOList = resourceMapper.queryRoleResource(roleId);
                if (CollectionUtil.isNotEmpty(resourceVOList)) {
                    List<E3ResourceVO> resourceTree = CollectionsUtils.generateResourceTree(resourceVOList, Base.STR0);
                    menuTreeMap.put(roleId, resourceTree);
                }
            });
        }
        log.info("---------------------初始化资源树完成---------------------");
        return menuTreeMap;
    }

    /**
     * 启动时加载各个角色菜单树
     *
     * @return 角色对应菜单树集合
     */
    @Bean("loadMenuTreeCache")
    @DependsOn({"e3ResourceMapper", "e3RoleMapper"})
    @SuppressWarnings("unchecked")
    public ConcurrentHashMap<String, List<E3ResourceVO>> loadMenuTreeCache() {
        return (ConcurrentHashMap<String, List<E3ResourceVO>>) initCaffeineCache().get(E3CacheKeyEnum.MENU_TREE.getKey(), (k) ->
                loadMenuTree());
    }
}
